package com.kuaishou;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import static org.bytedeco.javacpp.avformat.av_register_all;

public class KpgUtils {

    public static void main(String[] args) throws Exception {
        av_register_all();
//        String path = "D:\\myfile\\ZH1190\\Desktop\\extra\\ww.kpg";
        if(args.length < 1){
            throw new RuntimeException("请输入文件地址");
        }
        String path = args[0];
        videoImage(path);
    }

    /**
     * 截取视频第0帧的图片
     */
    public static void videoImage(String filePath) throws FrameGrabber.Exception {
        File targetDir = new File(filePath);
        if (!targetDir.exists()) {
            throw new RuntimeException(String.format("File(%s) not exists", filePath));
        }
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);

        ff.start();
        org.bytedeco.javacv.Frame q = ff.grabImage();
        String path = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
        String fileName = filePath.substring(path.length());
        fileName = fileName.split("\\.")[0];

        // 执行截图并放入指定位置
        doExecuteFrame(q, path + File.separator + fileName + ".jpg", q.imageWidth, q.imageHeight);
        ff.stop();

    }
    /**
     * 截取缩略图
     */
    private static void doExecuteFrame(org.bytedeco.javacv.Frame f, String targetFilePath, int widthdist, int heightdist) {
        String imagemat = "jpg";
        if (null == f ) {
            return;
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bi = converter.getBufferedImage(f);
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bi, imagemat, os);
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            // 开始读取文件并进行压缩
            Image src = ImageIO.read(is);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

            //绘制图像  getScaledInstance表示创建此图像的缩放版本，返回一个新的缩放版本Image,按指定的width,height呈现图像
            //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

            //创建文件输出流
            FileOutputStream out = new FileOutputStream(targetFilePath);
            //将图片按JPEG压缩，保存到out中
            ImageIO.write(bi, imagemat, out);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(tag);
            //关闭文件输出流
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
